#!/usr/bin/env bash

function helpinfo()
{
# 帮助信息
cat <<HELP
Usage: run_Anolis_remediation_kit.sh [OPTION]... FILE...
Execute the repair script based on the entry in the configuration file.

    -H    display this help and exit
    -c    Customize the configuration file.
          default:Anolis_security_benchmark_level1.config

HELP
} 

function assignPath()
{
# 根据编号确定修复脚本路径
    Dir=""
    if [[ `echo $line | cut -d "." -f1` == "1" ]] ; then
        Dir="$current_path/../../remediation-kits/access-and-control/"
    elif [[ `echo $line | cut -d "." -f1` == "2" ]] ; then
        Dir="$current_path/../../remediation-kits/logging-and-auditing/"
    elif [[ `echo $line | cut -d "." -f1` == "3" ]] ; then
        Dir="$current_path/../../remediation-kits/services/"
    elif [[ `echo $line | cut -d "." -f1` == "4" ]] ; then
        Dir="$current_path/../../remediation-kits/system-configurations/"
    elif [[ `echo $line | cut -d "." -f1` == "5" ]] ; then
        Dir="$current_path/../../remediation-kits/mandatory-access-control/"
    fi
}

function executeScripts()
{
# 执行修复脚本
    for line in `cat $config`; do
        assignPath
        if [[ ! -z "$Dir" ]] ; then
            cd $Dir # 切换至修复脚本所在目录
            number=$line
            filename=`ls | grep -P "^$number\-.*.sh$"` # 根据编号查询修复脚本完整文件名
            if [[ -a $filename ]] ; then
                echo "---Executing the script: $filename---"
                sh $filename
                echo "$filename Script executed `date +%Y_%m_%d-%T`" >> $current_path/log/$logfile # 记录脚本执行日志，增加时间戳
            elif [[ ! -a $filename ]] ; then
                echo "No $line Script" >> $current_path/log/$logfile # 记录没有对应修复脚本的编号
            fi
            cd $current_path # 返回修复工具主目录
        else
            echo "$line path error!" >> $current_path/log/$logfile # 记录没有对应路径的编号
        fi
    done
    echo "Execution log is saved in: $current_path/log/$logfile" # 展示日志文件名及路径
}

function main() {
# 主方法
    current_path="$(cd $(dirname $0);pwd)" # 获取绝对路径
    [ -z $config ] && config="$current_path/config/Anolis_security_benchmark_level1.config" # 确定config文件
    [ ! -e "$current_path/log" ] && mkdir $current_path/log # 创建log目录
    logfile=remediation-kits`date +%Y_%m_%d_%N`.log # 生成本次日志文件名

    executeScripts
}

# 验证操作系统是否符合加固要求（Anolis 8）
# systemVersion=false
# cat /etc/redhat-release | grep -Pq "^Anolis\s+OS\s+release\s+8.*" && systemVersion=true

if [[ -z $1 ]] ; then # 没有参数直接执行默认加固
    config=""
    main
elif [[ $# -eq 2 && $1 == "-c" ]] ; then # -c参数 指定自定义config
    if [[ -f $2 ]] ; then # 判断config文件是否存在
        echo "configfile is: $2"
        config=$2
        main
    else
        echo "$2 is not the correct configuration file."
    fi
else
    helpinfo
fi
